package com.dsit.hb950;

import android.net.Credentials;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;

import de.greenrobot.event.EventBus;


public class CanServerRunnable {
	private static final String TAG = "CAN ServerRunnable";
	private static final String SOCKET_NAME = "com.dsit.can";
	Thread acceptThrad;

	public  interface ReceiveListener{
		void onLocalsocketReceived(byte[] data,int len);
	}
	ReceiveListener receiveListener;

	public CanServerRunnable(){
		acceptThrad = new Thread(new Runnable() {
			@Override
			public void run() {
				LocalServerSocket srv = null;
				try {
					srv = new LocalServerSocket(SOCKET_NAME);
					while (true){
						Log.e(TAG, "wait for socket client connection --------<");
						LocalSocket client = srv.accept();
						Log.e(TAG, "new client connected! ");
						Credentials cre = client.getPeerCredentials();
						Log.i(TAG, "accept socket uid:" + cre.getUid());
						handleClient(client);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		acceptThrad.start();
	}

	void handleClient(LocalSocket client){
		ClientThread th = new ClientThread(client);
		th.start();
	}

	public void setReceiveListener(ReceiveListener listener){
		receiveListener = listener;
	}

	class ClientThread extends Thread {
		LocalSocket connect;
		InputStream in;
        boolean isRunning = true;
        byte[] buffer = new byte[1024];

		public ClientThread(LocalSocket client){
			connect = client;
		}
		@Override
		public void run() {
			int len;
			try {
				in = connect.getInputStream();
				while (isRunning && !interrupted()) {
					len=in.read(buffer);
					if(len == -1)
						continue;

					Log.i(TAG, "read can data --------< "+len + "bytes");
					if(receiveListener!=null){
						receiveListener.onLocalsocketReceived(buffer,len);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
				Log.e(TAG, "Error canbus " + e.getMessage());
			}
			finally{
				Log.e(TAG, "finally error");
				isRunning = false;
				try {
					connect.close();
                    if(in!=null) {
                        in.close();
                    }
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}